package com.xpgk.mvc.organization;

import java.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.binary.Base64;

import com.jfinal.aop.Before;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.xpgk.dto.RenderBean;
import com.xpgk.dto.ZtreeNode;
import com.xpgk.mvc.base.BaseController;
import com.xpgk.mvc.user.User;
import com.xpgk.tools.ToolRandoms;
import com.xpgk.tools.security.ToolIDEA;
import com.xpgk.tools.security.ToolPbkdf2;

public class OrganizationController extends BaseController {

	private OrganizationService organizationService;

	public void index() {
		Organization  organ =  Organization.dao.findById(getCUserOrganIds());
//		setAttr("level", organ.getInt(Organization.column_level));
		setAttr("level", organ.getBigDecimal(Organization.column_level).intValue());
		setAttr("organ", organ);
		render("organization.html");
	}

	/**
	 * 机构tree节点数据
	 */
	public void treeData() {
		List<ZtreeNode> nodeList = organizationService.childNodeData(getCxt(), ids, getCUserOrganIds());
		for (ZtreeNode ztreeNode : nodeList) {
			ztreeNode.setOpen("true");
		}
		renderJson(nodeList);
	}
	
	/**
	 * 跳转至添加
	 */
	public void toAdd() {
		Organization  organ =  Organization.dao.findById(ids);
		setAttr("organ", organ);
		setAttr("curOrgan", Organization.dao.findById(getCUserOrganIds()));
		String organIds = ToolRandoms.getUuid(true);
		setAttr("organIds", organIds);
//		if(organ.getBigDecimal(Organization.column_level).intValue()==1){
//			render("addOrgan1.html");
//		}else if(organ.getBigDecimal(Organization.column_level).intValue()==2){
//			render("addOrgan2.html");
//		}else if(organ.getBigDecimal(Organization.column_level).intValue()==3){
//			render("addOrgan3.html");
//		}
		render("addOrgan.html");
	}

	/**
	 * 添加权限tree节点
	 */
	public void rightTreeData() {
		List<ZtreeNode> nodeList = organizationService.rightChildNodeData(getCxt(), ids, getParaToInt("level"));
		renderJson(nodeList);
	}

	/**
	 * 添加机构
	 * @throws Exception 
	 */
	@Before(OrganizationValidator.class)
	public void addOrgan() throws Exception{
		List<ZtreeNode> nodes = getBeans(ZtreeNode.class);
		Organization organ = getModel(Organization.class);
		User user = getModel(User.class);
		RenderBean renderBean = organizationService.addOrgan(nodes, organ, user,getPara("organIds"));
		renderJson(renderBean);
	}
	


	/**
	 * 跳转至更新
	 */
	public void toUpdate() {
		Organization organ =  Organization.dao.findById(ids);
		setAttr("organ",organ );
		setAttr("curOrganIds", getCUserOrganIds());
//		if(organ.getBigDecimal(Organization.column_level).intValue()==1){
//			render("upOrgan1.html");
//		}else if(organ.getBigDecimal(Organization.column_level).intValue()==3){
//			render("upOrgan2.html");
//		}else if(organ.getBigDecimal(Organization.column_level).intValue()==4){
//			render("upOrgan3.html");
//		}
		render("upOrgan.html");
	}
	
	/**
	 * 修改机构
	 */
	@Before(OrganizationValidator.class)
	public void upOrgan() {
		List<ZtreeNode> changeNodes = getBeans(ZtreeNode.class);
		Organization organ = getModel(Organization.class);
		User user = getModel(User.class);
		RenderBean renderBean = organizationService.upOrgan(changeNodes, organ, user);
		renderJson(renderBean);
	}
	
	/**
	 * 修改权限tree节点
	 */
	public void upRightTreeData() {
		List<ZtreeNode> nodeList = organizationService.upRightChildNodeData(getCxt(), ids, getParaToInt("level"), getPara("stationIds"));
		renderJson(nodeList);
	}

	
	/**
	 * 修改权限tree节点
	 */
	public void upRightTreeData2() {
		String organIds =  getPara("stationIds");
		String stationIds = "";
		String sqlstationIds = "SELECT sds.ids FROM sys_dept_station sds WHERE sds.organIds =?";
		if(Db.findFirst(sqlstationIds,organIds)!=null){
			stationIds = Db.findFirst(sqlstationIds,organIds).getStr("ids");
		}
		
		List<ZtreeNode> nodeList = organizationService.upRightChildNodeData(getCxt(), ids, getParaToInt("level"),stationIds);
		renderJson(nodeList);
	}

	/**
	 * 市场负责人下拉tree
	 */
	public void mangerSelect() {
		List<ZtreeNode> nodeList = organizationService.allOrganUserList(getCxt(), ids, getPara("organIds"));
		renderJson(nodeList);
	}
	

	/**
	 * 查看用户信息
	 */
	public void lookUserInfo() {
		User user = User.dao.findById(ids);
		setAttr("userInfo", user);
		render("userInfo.html");
	}

	/**
	 * 机构用户列表
	 */
	public void organUserList() {
		String json = paging(splitPage, User.sqlId_splitPageSelect, User.sqlId_splitPageFrom);
		renderJson(json);
	}
	/**
	 * 禁用下级机构用户
	 */
	public void jyUser() {
		String userIds = getPara("ids");
		String msg = "200";
		User user = User.dao.findById(userIds);
		if(user!=null){
			if(user.getStr(User.column_status).equals("0")){
				user.set(User.column_status, "1");
				if(!user.update()){
					msg = "启用失败！";
				}
			}else if(user.getStr(User.column_status).equals("1")){
				user.set(User.column_status, "0");
				if(!user.update()){
					msg = "禁用失败！";
				}
			}
		}
		renderText(msg);
	}
	
	
	/**
	 * 重置下级机构用户密码
	 */
	public void initPass() {
		String userIds = getPara("ids");
		String msg = "200";
		User user = User.dao.findById(userIds);
		if(user!=null){
			try {
				// 密码加密
				byte[] salt = ToolPbkdf2.generateSalt();// 密码盐
				byte[] encryptedPassword = ToolPbkdf2.getEncryptedPassword("888888", salt);
				user.set(User.column_salt, Base64.encodeBase64String(salt));
				user.set(User.column_password, Base64.encodeBase64String(encryptedPassword));

				// 初始化idea密钥
				String secretKey = Base64.encodeBase64String(ToolIDEA.initKey());
				user.set(User.column_secretkey, secretKey);
				
				if(!user.update()){
					msg = "重置密码失败！";
				}

				
				// 缓存
				User.cacheAdd(user.getPKValue());
			} catch (NoSuchAlgorithmException e) {
				throw new RuntimeException("保存用户密码加密操作异常1", e);
			} catch (InvalidKeySpecException e) {
				throw new RuntimeException("保存用户密码加密操作异常2", e);
			} catch (Exception e) {
				throw new RuntimeException("保存用户异常", e);
			}
		}
		renderText(msg);
	}
	

	/**
	 * 机构列表
	 */
	public void organList() {
		String parentIds = (String) splitPage.getQueryParam().get("parentIds");
		if (ZBIDS.equals(parentIds)) {
			splitPage.getQueryParam().remove("parentIds");
			splitPage.getQueryParam().put("level", "2");
		}
		String json = paging(splitPage, Organization.sqlId_splitPageSelect, Organization.sqlId_splitPageFrom);
		renderJson(json);
	}
	
	/**
	 * 删除机构
	 */
	public void delOrgan(){
		String result = organizationService.delete(ids);
		renderText(result);
	}

	/**
	 * 根据用户查询机构列表
	 */
	public void getORGAN() {
		String ids = getCUserOrganIds();
		Organization organ = Organization.dao.findById(ids);
		String LEVELNUM = organ.get(Organization.column_level).toString();
		List<Organization> listorgan = null;
		if ("0".equals(LEVELNUM) || "1".equals(LEVELNUM) || "2".equals(LEVELNUM) ) {
			listorgan = organizationService.getORGAN(ids, ids);
		}else{
			listorgan = new ArrayList<>();
			listorgan.add(organ);
		}
		renderJson(listorgan);
	}
}
